//
//  TextGirdsCell.swift
//  AmountBody
//
//  Created by Qiu Jishuai on 2018/2/1.
//  Copyright © 2018年 RCMTM. All rights reserved.
//

import Foundation

class JSFromCell: CALayer {

    typealias Config = (string: NSAttributedString, scale: CGFloat)

    var defaultFont: UIFont!
    var defaultTextColor: UIColor!
    var itemLayers: [CATextLayer] = []

    var cellHeight: CGFloat = 0

    var configs: [JSFromCellItemConfig] = [] {
        didSet {
            let targetCount = configs.count
            while itemLayers.count > targetCount {
                itemLayers.removeLast().removeFromSuperlayer()
            }
            while itemLayers.count < targetCount {
                let textLayer = CATextLayer()
                //                      textLayer.shouldRasterize = true
                textLayer.isWrapped = true
                self.backgroundColor = UIColor.random().cgColor
                textLayer.alignmentMode = kCAAlignmentJustified
                textLayer.contentsScale = UIScreen.main.scale
                textLayer.truncationMode = kCATruncationEnd
                itemLayers.append(textLayer)
                addSublayer(textLayer)
            }
            //设置文字
            for (index, config) in configs.enumerated() {
                let textLayer = itemLayers[index]
                if let attributeText = config.attributeText {
                    textLayer.string = attributeText
                } else {
                    textLayer.string = config.text
                    let font: UIFont = config.font ?? self.defaultFont
                    textLayer.fontSize = font.pointSize
                    textLayer.font = font.ctFontRef()
                    textLayer.foregroundColor = config.textColor?.cgColor ?? self.defaultTextColor.cgColor
                }
                textLayer.alignmentMode = config.alignment.asCAAlignment
            }
            layoutItemLayers()
        }
    }

    func layoutItemLayers() {
        for (index, config) in configs.enumerated() {
            let insets = config.insets
            //宽度等于计算的比例加上config的insets
            let sublayerWidth = config.scale * width
            //高度等于计算出的宽度加上config的insets
            let sublayerHeight = ((config.text ?? "") as NSString).height(for: config.font ?? defaultFont, width: sublayerWidth)

            var x = insets.left
            if index != 0 {
                x += itemLayers[index - 1].frame.maxX + configs[index - 1].insets.right
            }

            let y: CGFloat = insets.top
            let frame = CGRect(x: x, y: y, width: sublayerWidth, height: sublayerHeight)
            itemLayers[index].frame = frame
        }
        cellHeight = itemLayers.enumerated().map({ (index, layer) in
            layer.frame.maxY + configs[index].insets.bottom
        }).max() ?? 0
    }
}
